"use client";
import { useEffect, useState, useRef, useCallback } from 'react';
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Play, Pause, RotateCw } from "lucide-react";

const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${secs.toString().padStart(2, '0')}`;
};

const Timer = () => {
  const [inputMinutes, setInputMinutes] = useState<number>(25);
  const [remainingSeconds, setRemainingSeconds] = useState<number>(25 * 60);
  const [isRunning, setIsRunning] = useState(false);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const timerRef = useRef<NodeJS.Timeout>();
  const speechSynth = useRef<SpeechSynthesis | null>(null);

  // 确保基础数据计算安全
  const totalSeconds = inputMinutes * 60;
  const elapsedSeconds = totalSeconds - Math.max(0, remainingSeconds);
  const progress = totalSeconds > 0 ? (elapsedSeconds / totalSeconds) * 100 : 0;

  // 可靠的背景色计算
  const getEmergencyColor = useCallback(() => {
    if (!isRunning) return '#f8fafc'; // 默认浅灰色
    if (remainingSeconds <= 300 && remainingSeconds > 0) {
      const intensity = 255 - Math.floor((remainingSeconds / 300) * 200);
      return `rgb(255,${Math.max(50, intensity)},${Math.max(50, intensity)})`;
    }
    return '#f1f5f9'; // 运行状态基础色
  }, [isRunning, remainingSeconds]);

  useEffect(() => {
    audioRef.current = new Audio('https://download-cos.yofish.com/jsptceph-1257588738-shenghuozhibei/20250217194156776-buguniao.mp3');
    speechSynth.current = window.speechSynthesis;
    return () => clearInterval(timerRef.current);
  }, []);

  useEffect(() => {
    if (isRunning) {
      timerRef.current = setInterval(() => {
        setRemainingSeconds(prev => Math.max(0, prev - 1));
      }, 1000);
    }
    return () => clearInterval(timerRef.current);
  }, [isRunning]);

  return (
    <div className="min-h-screen flex flex-col items-center justify-center p-4 transition-colors duration-300"
         style={{ backgroundColor: getEmergencyColor() }}>
      
      {/* 稳定的主容器 */}
      <div className={`bg-white rounded-xl shadow-lg p-8 w-full max-w-md space-y-6 border-2 ${
        remainingSeconds <= 300 && isRunning ? 
        'border-red-500 animate-pulse' : 
        'border-gray-200'
      }`}>
        
        {/* 输入模块 */}
        <div className="text-center space-y-4">
          <h1 className="text-2xl font-bold text-gray-800">倒计时设置</h1>
          <div className="flex items-center justify-center space-x-3">
            <Input
              type="number"
              value={inputMinutes}
              onChange={(e) => {
                const value = Math.max(1, Math.min(999, Number(e.target.value)));
                setInputMinutes(value);
                if (!isRunning) setRemainingSeconds(value * 60);
              }}
              className="w-24 text-center text-xl border-2 border-blue-500 font-bold text-blue-800"
              min="1"
              max="999"
              disabled={isRunning}
            />
            <span className="text-lg text-gray-600">分钟</span>
          </div>
        </div>

        {/* 时间显示模块 */}
        <div className="grid grid-cols-2 gap-4 text-center">
          <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
            <p className="text-sm text-blue-600 mb-1">已过时间</p>
            <div className="text-3xl font-bold text-blue-800">
              {formatTime(elapsedSeconds)}
            </div>
          </div>
          <div className="bg-red-50 p-4 rounded-lg border border-red-200">
            <p className="text-sm text-red-600 mb-1">剩余时间</p>
            <div className={`text-3xl font-bold ${
              remainingSeconds <= 300 && isRunning ? 
              'text-red-800 animate-bounce' : 
              'text-red-700'
            }`}>
              {formatTime(remainingSeconds)}
            </div>
          </div>
        </div>

        {/* 进度条 */}
        <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
          <div 
            className={`h-full transition-all duration-300 ${
              remainingSeconds <= 300 && isRunning ?
              'bg-gradient-to-r from-red-500 to-pink-500' :
              'bg-gradient-to-r from-blue-500 to-purple-500'
            }`}
            style={{ width: `${progress}%` }}
          />
        </div>

        {/* 控制按钮 */}
        <div className="flex justify-center space-x-3">
          <Button 
            onClick={() => setIsRunning(!isRunning)}
            className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white"
          >
            {isRunning ? (
              <Pause className="mr-2 h-5 w-5" />
            ) : (
              <Play className="mr-2 h-5 w-5" />
            )}
            {isRunning ? '暂停' : remainingSeconds === 0 ? '开始' : '继续'}
          </Button>
          <Button 
            variant="outline" 
            onClick={() => {
              setIsRunning(false);
              setRemainingSeconds(inputMinutes * 60);
            }}
            className="text-gray-700 border-gray-300 hover:bg-gray-50"
          >
            <RotateCw className="mr-2 h-5 w-5" /> 重置
          </Button>
        </div>
      </div>
    </div>
  );
};

export default Timer;
